<template>
  <van-pull-refresh v-model="refreshing"
    :disabled="supportSelect || pullDisabled"
    :style="{height: height}"
    @refresh="onRefresh"
  >
    <van-list
      ref="scrollBox"
      style="height: 100%;"
      :style="{ 'overflow-y': scrollY ? 'auto' : 'hidden'}"
      v-model="isLoading"
      :finished="finished || supportSelect"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
      @load="onLoad"
    >
      <van-empty v-if="dataList.length <= 0" style="height: 100%;" description="暂无数据" />
      <template v-else v-for="data in dataList">
        <slot :data="data" />
      </template>
    </van-list>
  </van-pull-refresh>
</template>

<script>
export default {
  name: 'customList',
  props: {
    loadData: {
      type: Function
    },
    rowKey: {
      type: String
    },
    supportSelect: {
      type: Boolean,
      default: false
    },
    supportPullRefresh: {
      type: Boolean,
      default: true
    },
    scrollY: {
      type: Boolean,
      default: true
    },
    height: {
      type: String
    }
  },
  data () {
    return {
      refreshing: false,
      isLoading: false,
      finished: false,
      error: false,
      pullDisabled: false,
      pageNum: 1,
      dataList: []
    }
  },
  methods: {
    reset () {
      this.pageNum = 1;
      this.dataList = [];
      this.onLoad();
    },
    onRefresh () {
      this.onLoad();
    },
    onLoad () {
      if (typeof this.loadData === 'function') {
        this.isLoading = true;
        if (this.refreshing) {
          this.pageNum = 1;
        }
        this.loadData(this.pageNum).then(res => {
          if (this.rowKey != null && this.rowKey !== '') {
            // 根据每行数组的唯一字段，合并显示数据
          }
          if (this.refreshing) this.dataList = [];
          this.dataList = this.dataList.concat(res.dataList);
          this.error = false;
          this.isLoading = false;
          // 如果返回的结果里指定了finished，使用指定的finished，否则根据是否返回空数据判断
          if (res.finished != null) {
            this.finished = res.finished;
          } else {
            this.finished = res.dataList.length <= 0;
          }
          this.refreshing = false;
          this.pageNum++;
        }).catch(e => {
          console.log(e);
          this.error = true;
          this.refreshing = false;
        });
      }
    },
    getDataList () {
      return this.dataList;
    },
    setPullDisabled () {
      let scrollBox = this.$refs.scrollBox;
      if (scrollBox) {
        this.pullDisabled = scrollBox.$el.scrollTop > 0;
      }
    }
  },
  mounted () {
    let scrollBox = this.$refs.scrollBox;
    if (scrollBox) {
      scrollBox.$el.addEventListener('scroll', this.setPullDisabled);
    }
  },
  beforeDestroy () {
    let scrollBox = this.$refs.scrollBox;
    if (scrollBox) {
      scrollBox.$el.removeEventListener('scroll', this.setPullDisabled);
    }
  }
}
</script>

<style>
</style>
